<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <el-row :gutter="20">
        <el-col :span="18">
          <h2>智能排课管理</h2>
          <p class="page-description">基于遗传算法的智能排课系统，支持多种约束条件和优化目标</p>
        </el-col>
        <el-col :span="6" class="text-right">
          <el-button type="primary" icon="el-icon-plus" @click="handleCreateTask">创建排课任务</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon running">
              <i class="el-icon-loading"></i>
            </div>
            <div class="stats-info">
              <h3>{{ runningTasksCount }}</h3>
              <p>正在执行</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon completed">
              <i class="el-icon-check"></i>
            </div>
            <div class="stats-info">
              <h3>{{ completedTasksCount }}</h3>
              <p>已完成</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon failed">
              <i class="el-icon-close"></i>
            </div>
            <div class="stats-info">
              <h3>{{ failedTasksCount }}</h3>
              <p>执行失败</p>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon total">
              <i class="el-icon-document"></i>
            </div>
            <div class="stats-info">
              <h3>{{ totalTasksCount }}</h3>
              <p>总任务数</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 查询条件 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input
            v-model="queryParams.taskName"
            placeholder="请输入任务名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="学期" prop="semester">
          <el-select v-model="queryParams.semester" placeholder="请选择学期" clearable>
            <el-option
              v-for="semester in semesterOptions"
              :key="semester.value"
              :label="semester.label"
              :value="semester.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="待执行" value="PENDING" />
            <el-option label="执行中" value="RUNNING" />
            <el-option label="已完成" value="COMPLETED" />
            <el-option label="已失败" value="FAILED" />
            <el-option label="已取消" value="CANCELLED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleCreateTask"
            v-hasPermi="['jwgl:schedule:task:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['jwgl:schedule:task:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['jwgl:schedule:task:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['jwgl:schedule:task:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </el-card>

    <!-- 任务列表 -->
    <el-card>
      <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="任务ID" align="center" prop="id" width="80" />
        <el-table-column label="任务名称" align="center" prop="taskName" :show-overflow-tooltip="true" />
        <el-table-column label="学期" align="center" prop="semester" width="120" />
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template slot-scope="scope">
            <el-tag
              :type="getStatusTagType(scope.row.status)"
              disable-transitions
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="进度" align="center" prop="progress" width="120">
          <template slot-scope="scope">
            <el-progress
              :percentage="scope.row.progress || 0"
              :status="getProgressStatus(scope.row.status)"
              :stroke-width="8"
            ></el-progress>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" align="center" prop="startTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleDetail(scope.row)"
              v-hasPermi="['jwgl:schedule:task:query']"
            >详情</el-button>
            <el-button
              v-if="scope.row.status === 'PENDING'"
              size="mini"
              type="text"
              icon="el-icon-video-play"
              @click="handleStart(scope.row)"
              v-hasPermi="['jwgl:schedule:task:start']"
            >启动</el-button>
            <el-button
              v-if="scope.row.status === 'RUNNING'"
              size="mini"
              type="text"
              icon="el-icon-video-pause"
              @click="handleStop(scope.row)"
              v-hasPermi="['jwgl:schedule:task:stop']"
            >停止</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['jwgl:schedule:task:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['jwgl:schedule:task:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 创建任务对话框 -->
    <el-dialog title="创建排课任务" :visible.sync="createDialogVisible" width="600px" append-to-body>
      <create-task-form
        v-if="createDialogVisible"
        @success="handleCreateSuccess"
        @cancel="createDialogVisible = false"
      />
    </el-dialog>

    <!-- 任务详情对话框 -->
    <el-dialog title="任务详情" :visible.sync="detailDialogVisible" width="800px" append-to-body>
      <task-detail
        v-if="detailDialogVisible"
        :task-id="selectedTaskId"
        @close="detailDialogVisible = false"
      />
    </el-dialog>

    <!-- 添加或修改任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="学期" prop="semester">
          <el-select v-model="form.semester" placeholder="请选择学期">
            <el-option
              v-for="semester in semesterOptions"
              :key="semester.value"
              :label="semester.label"
              :value="semester.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listScheduleTask,
  getScheduleTask,
  delScheduleTask,
  addScheduleTask,
  updateScheduleTask,
  startScheduleTask,
  stopScheduleTask,
  getRunningTasks,
  exportScheduleTask
} from '@/api/jwgl/scheduleTask'
import CreateTaskForm from './components/CreateTaskForm'
import TaskDetail from './components/TaskDetail'

export default {
  name: 'ScheduleTask',
  components: {
    CreateTaskForm,
    TaskDetail
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 智能排课任务表格数据
      taskList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 创建任务对话框
      createDialogVisible: false,
      // 任务详情对话框
      detailDialogVisible: false,
      // 选中的任务ID
      selectedTaskId: null,
      // 统计数据
      runningTasksCount: 0,
      completedTasksCount: 0,
      failedTasksCount: 0,
      totalTasksCount: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskName: null,
        semester: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskName: [
          { required: true, message: '任务名称不能为空', trigger: 'blur' }
        ],
        semester: [
          { required: true, message: '学期不能为空', trigger: 'change' }
        ]
      },
      // 学期选项
      semesterOptions: [
        { label: '2024-2025学年第一学期', value: '2024-2025-1' },
        { label: '2024-2025学年第二学期', value: '2024-2025-2' },
        { label: '2025-2026学年第一学期', value: '2025-2026-1' },
        { label: '2025-2026学年第二学期', value: '2025-2026-2' }
      ]
    }
  },
  created() {
    this.getList()
    this.getStatistics()
  },
  methods: {
    /** 查询智能排课任务列表 */
    getList() {
      this.loading = true
      listScheduleTask(this.queryParams).then(response => {
        this.taskList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 获取统计数据 */
    getStatistics() {
      // 获取正在执行的任务数量
      getRunningTasks().then(response => {
        this.runningTasksCount = response.data ? response.data.length : 0
      })
      
      // 统计各状态任务数量
      listScheduleTask({ pageNum: 1, pageSize: 1000 }).then(response => {
        const tasks = response.rows || []
        this.totalTasksCount = tasks.length
        this.completedTasksCount = tasks.filter(task => task.status === 'COMPLETED').length
        this.failedTasksCount = tasks.filter(task => task.status === 'FAILED').length
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        taskName: null,
        semester: null,
        status: null,
        progress: null,
        startTime: null,
        endTime: null,
        errorMessage: null,
        configData: null,
        resultData: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 创建任务按钮操作 */
    handleCreateTask() {
      this.createDialogVisible = true
    },
    /** 创建任务成功回调 */
    handleCreateSuccess() {
      this.createDialogVisible = false
      this.getList()
      this.getStatistics()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加智能排课任务'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getScheduleTask(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改智能排课任务'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateScheduleTask(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addScheduleTask(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除智能排课任务编号为"' + ids + '"的数据项？').then(function() {
        return delScheduleTask(ids)
      }).then(() => {
        this.getList()
        this.getStatistics()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 启动任务 */
    handleStart(row) {
      this.$modal.confirm('确认启动任务"' + row.taskName + '"？').then(() => {
        return startScheduleTask(row.id)
      }).then(() => {
        this.$modal.msgSuccess('任务启动成功')
        this.getList()
        this.getStatistics()
      }).catch(() => {})
    },
    /** 停止任务 */
    handleStop(row) {
      this.$modal.confirm('确认停止任务"' + row.taskName + '"？').then(() => {
        return stopScheduleTask(row.id)
      }).then(() => {
        this.$modal.msgSuccess('任务停止成功')
        this.getList()
        this.getStatistics()
      }).catch(() => {})
    },
    /** 查看详情 */
    handleDetail(row) {
      this.selectedTaskId = row.id
      this.detailDialogVisible = true
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('jwgl/schedule/task/export', {
        ...this.queryParams
      }, `task_${new Date().getTime()}.xlsx`)
    },
    /** 获取状态标签类型 */
    getStatusTagType(status) {
      const statusMap = {
        'PENDING': 'info',
        'RUNNING': 'warning',
        'COMPLETED': 'success',
        'FAILED': 'danger',
        'CANCELLED': 'info'
      }
      return statusMap[status] || 'info'
    },
    /** 获取状态文本 */
    getStatusText(status) {
      const statusMap = {
        'PENDING': '待执行',
        'RUNNING': '执行中',
        'COMPLETED': '已完成',
        'FAILED': '已失败',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || '未知'
    },
    /** 获取进度条状态 */
    getProgressStatus(status) {
      if (status === 'COMPLETED') return 'success'
      if (status === 'FAILED') return 'exception'
      return null
    }
  }
}
</script>

<style lang="scss" scoped>
.page-header {
  margin-bottom: 20px;
  
  h2 {
    margin: 0;
    color: #303133;
    font-size: 24px;
    font-weight: 500;
  }
  
  .page-description {
    margin: 8px 0 0 0;
    color: #909399;
    font-size: 14px;
  }
}

.stats-cards {
  margin-bottom: 20px;
  
  .stats-card {
    .stats-content {
      display: flex;
      align-items: center;
      
      .stats-icon {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;
        
        i {
          font-size: 24px;
          color: #fff;
        }
        
        &.running {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        &.completed {
          background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }
        
        &.failed {
          background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }
        
        &.total {
          background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
        }
      }
      
      .stats-info {
        h3 {
          margin: 0;
          font-size: 28px;
          font-weight: 600;
          color: #303133;
        }
        
        p {
          margin: 4px 0 0 0;
          font-size: 14px;
          color: #909399;
        }
      }
    }
  }
}

.search-card {
  margin-bottom: 20px;
}

.text-right {
  text-align: right;
}
</style>